/*
Copyright (C) 2010  Christoph Schnack, Berlin (Germany)

This file is part of Tribuit.

    Tribuit is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Tribuit is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Tribuit.  If not, see <http://www.gnu.org/licenses/>.
*/
package Settings;

import java.awt.Dimension;
import java.io.*;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.logging.*;
import javax.swing.*;
import GuiTools.CustomTextArea;
import GuiTools.GuiTools;
import GuiTools.TribuitFrame;

public class TribuitLogger{
	Logger logger;
	FileHandler fh;
	TribuitFrame MAINFRAME;
	Integer highest;
	
	public TribuitLogger(TribuitFrame mf) {
		MAINFRAME = mf;
	    logger = Logger.getLogger("tribuitLog");
		try {
			File f = new File(GuiTools.TRIBUITHOME+File.separator+"log");
			f.mkdir();
			fh = new FileHandler(GuiTools.TRIBUITHOME+File.separator+"log"+File.separator+"logFile.log", false);
			logger.addHandler(fh);
			logger.setLevel(Level.ALL);
			SimpleFormatter formatter = new SimpleFormatter();
			fh.setFormatter(formatter);
			Thread.setDefaultUncaughtExceptionHandler(new TribuitExceptionHandler());
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void logException(Throwable e){
		logger.log(Level.ALL,"EXCEPTION",e);
		Integer current;
		highest = 1;
		final StringBuffer sb = new StringBuffer();;
		File dir = new File(GuiTools.TRIBUITHOME+File.separator+"log");
		for(File f : dir.listFiles()){
			if(f.getName().startsWith("error")){
				current = Integer.parseInt(f.getName().substring(5,f.getName().length()));
				if(current.equals(highest))highest = ++current;
			}
		}
		try{
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(GuiTools.TRIBUITHOME+File.separator+"log"+File.separator+"error"+highest),"UTF-8"));
			BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(GuiTools.TRIBUITHOME+File.separator+"log"+File.separator+"logFile.log"),"UTF-8"));
			String line = null;
			while((line = reader.readLine()) != null){
				writer.write(line+"\n");
				sb.append(line+"\n");
			}
			reader.close();
			writer.close();
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		if(SwingUtilities.isEventDispatchThread()){
			showErrorMsg(sb,highest);
		}
		else{
			SwingUtilities.invokeLater(new Runnable(){
				public void run(){
					showErrorMsg(sb,highest);
				}
			});
		}
	}

	class TribuitExceptionHandler implements UncaughtExceptionHandler{
		public void uncaughtException(Thread threadArg, Throwable throwableArg) {
			logException(throwableArg);
		}
	}
	public void showErrorMsg(StringBuffer sb,int no){
		JScrollPane sp = new JScrollPane(new CustomTextArea(sb.toString()));
		sp.setPreferredSize(new Dimension(500,300));
		JLabel label = new JLabel("<HTML>An error occured and was logged in:<br>" +GuiTools.TRIBUITHOME+File.separator+"log"+File.separator+"error"+no+"<br><br>PLEASE MAIL THIS FILE TO tribuit@web.de<br><br>");
		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
		panel.add(label);
		panel.add(sp);
		String[] opts = {"exit","continue program"};
		int ans = JOptionPane.showOptionDialog(MAINFRAME,panel,"ERROR",JOptionPane.OK_CANCEL_OPTION,JOptionPane.ERROR_MESSAGE,null,opts,null);
		if(ans == JOptionPane.OK_OPTION){
			System.exit(0);
		}
	}

} 